﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using log4net;
using MMS.DAO;


namespace MMS
{
    public partial class FormLogin : Form
    {
        private static readonly ILog log =
            LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        public bool IsConnected;
        private BackgroundWorker backgroundWorker = new BackgroundWorker();
        private FormLoading formLoading = new FormLoading();
        public FormLogin()
        {
            InitializeComponent();
            this.Text = Utils.APP_TITLE;
            this.AcceptButton = btnLogin;
            this.CancelButton = btnExit;
            backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork);
            backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker_RunWorkerCompleted);
        }

        private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            try
            {
                this.Activate();
                formLoading.Hide();
                Result result = (Result)e.Result;
                if (result.IsSuccess)
                {
                    this.Close();
                }
                else
                {
                    Utils.ShowError(result.Message);
                    txtUserName.Focus();
                }

            }
            catch (Exception exception)
            {
                Utils.ShowError(exception.Message);
                log.Error("Login failed", exception);
                formLoading.Close();
            }
        }

        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            Result result = new Result();
            try
            {
                string userName = txtUserName.Text.Trim();
                string passwordMd5 = txtPassword.Text.Trim();
                if (!passwordMd5.Equals(Utils.GetConfigParam(Param.Password)))
                {
                    passwordMd5 = Utils.Md5(passwordMd5);
                }
                log.Error(string.Format("Login for user: {0} password: {1}", userName, passwordMd5));
                UserDAO userDAO = new UserDAO(Param.ConnectionString.Value);
                //Select user by user name
                UserDTO userDTO = userDAO.SelectUserByUserName(userName);

                if (userDTO != null && userDTO.Password.Equals(passwordMd5))
                {
                    Utils.UserLoggedIn = userDTO;
                    IsConnected = true;
                    result.IsSuccess = true;
                    result.Message = "Đăng nhập thành công";
                }
                else
                {
                    IsConnected = false;
                    result.IsSuccess = false;
                    result.Message = "Sai tên đăng nhập và/hoặc mật khẩu";
                }
            }
            catch (Exception exception)
            {
                log.Error(exception);
                result.IsSuccess = false;
                result.Message = exception.Message;
            }
            finally
            {
                e.Result = result;
            }
        }

        private void doLogin()
        {
            if (formLoading.IsDisposed)
                formLoading = new FormLoading();
            formLoading.Title = @"Đang đăng nhập hệ thống. Xin vui lòng đợi...";
            backgroundWorker.RunWorkerAsync();
            formLoading.ShowDialog();
        }

        private void control_Click(object sender, EventArgs e)
        {
            string controlName = ((Control)sender).Name;
            if (controlName == btnLogin.Name)
            {
                string userName = "", passwordMd5 = "";
                if (chkRememberPass.Checked)
                {
                    userName = txtUserName.Text.Trim();
                    passwordMd5 = txtPassword.Text.Trim();
                    if (!passwordMd5.Equals(Utils.GetConfigParam(Param.Password)))
                    {
                        passwordMd5 = Utils.Md5(passwordMd5);
                    }
                }
                Utils.SetConfigParam(Param.RememberPassword, chkRememberPass.Checked.ToString());
                Utils.SetConfigParam(Param.UserName, userName);
                Utils.SetConfigParam(Param.Password, passwordMd5);
                doLogin();
            }
            else if (controlName == btnExit.Name)
            {
                this.Close();
            }
            else if (controlName == llbConfig.Name)
            {
                FormConfig f = new FormConfig();
                f.ShowDialog();
            }
            else
            {
                log.Error(String.Format("Unknow control name {0}", controlName));
            }
        }

        private void FormLogin_Load(object sender, EventArgs e)
        {
            if (Boolean.Parse(Utils.GetConfigParam(Param.RememberPassword)))
            {
                txtUserName.Text = Utils.GetConfigParam(Param.UserName);
                txtPassword.Text = Utils.GetConfigParam(Param.Password);
                chkRememberPass.Checked = true;
            }
            else
            {
                chkRememberPass.Checked = false;
            }
        }

       

        
    }
}
